package cn.zzdt4j.common.toolkit;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Optional;

import static cn.zzdt4j.common.constant.Constants.EMTY_STRING;

/**
 * User context(Transition scheme)
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023/10/29 23:17
 */
public class UserContext {

    private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal<User>();

    public static void setUserInfo(String username, String userRole) {
        USER_THREAD_LOCAL.set(new User(username, userRole));
    }

    public static String getUserName(){
        return Optional.ofNullable(USER_THREAD_LOCAL.get()).map(User::getUsername).orElse("");
    }

    public static String getUserRole() {
        return Optional.ofNullable(USER_THREAD_LOCAL.get())
                .map(User::getUserRole)
                .orElse(EMTY_STRING);
    }

    public static void clear() {
        USER_THREAD_LOCAL.remove();
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class User {
        private String username;
        private String userRole;
    }
}
